package com.paygate.controller

import com.paygate.entity.RResult
import com.paygate.isNotNull
import org.springframework.http.HttpStatus
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice
import kotlin.contracts.ExperimentalContracts


@RestControllerAdvice
open class ExceptionHandler {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    open fun handleException(t: Throwable?): RResult<Any> {
        return RResult<Any>().apply {
            code = 500
            t.takeIf { it != null }?.run {
                msg = when (this) {
                    is BindException -> this.fieldErrors.joinToString { "${it.field} ${it.defaultMessage}" }
                    else -> this.message
                }
            }
        }
    }
}